package com.wolfalpha.utron.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.util.EMLog;
import com.wolfalpha.utron.R;
import com.wolfalpha.utron.activity.MainActivity;
import com.wolfalpha.utron.activity.NewTlzActivity;
import com.wolfalpha.utron.activity.UserInfoActivity;
import com.wolfalpha.utron.adapter.ItemPartnerAdapter;
import com.wolfalpha.utron.adapter.ItemProjectAttentionedAdapter;
import com.wolfalpha.utron.adapter.TlzAdapter;
import com.wolfalpha.utron.app.AppConfig;
import com.wolfalpha.utron.app.AppContext;
import com.wolfalpha.utron.bean.ItemPartner;
import com.wolfalpha.utron.bean.UserBaseInfo;
import com.wolfalpha.utron.service.PartnerService;
import com.wolfalpha.utron.service.impl.PartnerServiceImpl;
import com.wolfalpha.utron.ui.UIHelper;
import com.wolfalpha.utron.utils.ThreadPoolUtils;
import com.wolfalpha.utron.view.AlertDialog;
import com.wolfalpha.utron.view.list.WaterDropListView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import easemob.applib.controller.HXSDKHelper;
import easemob.chatuidemo.Constant;
import easemob.chatuidemo.DemoHXSDKHelper;
import easemob.chatuidemo.activity.ChatActivity;
import easemob.chatuidemo.activity.NewFriendsMsgActivity;
import easemob.chatuidemo.adapter.ChatAllHistoryAdapter;
import easemob.chatuidemo.adapter.ContactAdapter;
import easemob.chatuidemo.adapter.GroupAdapter;
import easemob.chatuidemo.db.UserDao;
import easemob.chatuidemo.domain.User;
import easemob.chatuidemo.utils.UserUtils;
import easemob.chatuidemo.widget.Sidebar;

/**
 * Created by luodon on 15/8/17.
 */
public class MainPartner extends Fragment implements WaterDropListView.IWaterDropListViewListener, View.OnClickListener {

    //对父Activity的接口
    private MainPartnerListener mlistener;

    private PartnerService partnerService;

    private WaterDropListView pListView;        //合伙人列表

    private List<ItemPartner> partners = new ArrayList<ItemPartner>();

    private ItemProjectAttentionedAdapter attentionedAdapter;
    private ItemPartnerAdapter partnerAdapter;

    private List<UserBaseInfo> baseInfos = new ArrayList<UserBaseInfo>();

    private int page = 1;

    private final int LOAD_MORE = 1;    //加载更多
    private final int LOAD_REFRESH = 2; //刷新
    private final int SHOW_STR = 3; //显示信息

    private List<Integer> level = new ArrayList<Integer>();
    private List<String> role = new ArrayList<String>();
    private List<String> times = new ArrayList<String>();

    private TextView tvFriendBarFriend; //好友bar
    private TextView tvFriendBarTlz;    //讨论组bar
    private TextView tvFriendBarJlq;    //交流群bar

    private LinearLayout llFriendFriend; //好友
    private LinearLayout llFriendTlz;    //讨论组
    private LinearLayout llFriendJlq;    //交流群

    /******聊天列表**********/
    /**
     * 聊天列表
     */
    private InputMethodManager inputMethodManager;
    private WaterDropListView mListView;
    private ChatAllHistoryAdapter adapterMessage;
    private EditText query;
    private ImageButton clearSearch;
    public RelativeLayout errorItem;

    public TextView errorText;
    private boolean hiddenMessage;
    private List<EMConversation> conversationList = new ArrayList<EMConversation>();

    /******
     * 聊天列表
     **********/

    /*******
     * 联系人列表
     **********/
    private ViewFlipper vfContacts;
    private int indexContact = 0;

    private ContactAdapter adapterContact;
    private List<User> contactList;
    private ListView cfListView;
    private boolean hiddenContact;
    private Sidebar sidebar;
    HXContactSyncListener contactSyncListener;
    //    HXBlackListSyncListener blackListSyncListener;
    HXContactInfoSyncListener contactInfoSyncListener;

    class HXContactSyncListener implements HXSDKHelper.HXSyncListener {
        @Override
        public void onSyncSucess(final boolean success) {
            EMLog.d(TAG, "on contact list sync success:" + success);
            getParentActivity().runOnUiThread(new Runnable() {
                public void run() {
                    getParentActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            if (success) {
                                friendsRefresh();
                            } else {
                                String s1 = "获取列表失败，请重试";
                                Toast.makeText(getParentActivity(), s1, Toast.LENGTH_SHORT).show();
                            }
                        }

                    });
                }
            });
        }
    }

//    class HXBlackListSyncListener implements HXSDKHelper.HXSyncListener {
//
//        @Override
//        public void onSyncSucess(boolean success) {
//            getParentActivity().runOnUiThread(new Runnable() {
//
//                @Override
//                public void run() {
//                    friendsRefresh();
//                }
//
//            });
//        }
//
//    }

    class HXContactInfoSyncListener implements HXSDKHelper.HXSyncListener {

        @Override
        public void onSyncSucess(final boolean success) {
            EMLog.d(TAG, "on contactinfo list sync success:" + success);
            if (success) {
                friendsRefresh();
            }
        }

    }

    /*group*/
    public static final String TAG = "Partner";
    private ListView groupListView;
    protected List<EMGroup> grouplist;
    private GroupAdapter groupAdapter;
    private GSyncListener gSyncListener;

    class GSyncListener implements HXSDKHelper.HXSyncListener {
        @Override
        public void onSyncSucess(final boolean success) {
            EMLog.d(TAG, "onSyncGroupsFinish success:" + success);
            groupRefresh();
        }
    }


    /*讨论组*/
    private ListView tlzListView;
    protected List<EMGroup> tlzlist;
    private TlzAdapter tlzAdapter;
    private TlzSyncListener tlzSyncListener;

    class TlzSyncListener implements HXSDKHelper.HXSyncListener {
        @Override
        public void onSyncSucess(final boolean success) {
            EMLog.d(TAG, "onSyncGroupsFinish success:" + success);
            friendsRefresh();
        }
    }


    /*******
     * 联系人列表
     **********/


    @Override
    public void onRefresh() {
        page = 1;
        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                partners = partnerService.getList(page, role, times, level);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (partners != null) {
                            partnerAdapter.setData(partners);
                            if (partners.size() < AppConfig.LIST_PAGE_SIZE) {
                                pListView.setPullLoadEnable(false);
                            } else {
                                pListView.setPullLoadEnable(true);
                            }
                        } else {
                            UIHelper.ToastMessage(getActivity(), "没有数据");
                            partnerAdapter.setData(new ArrayList<ItemPartner>());
                            pListView.setPullLoadEnable(false);
                        }
                        pListView.stopRefresh();
                    }
                });
            }
        });
    }

    @Override
    public void onLoadMore() {
        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                final List<ItemPartner> partners1 = partnerService.getList(++page, role, times, level);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (partners1 != null) {
                            partners.addAll(partners1);
                            partnerAdapter.setData(partners);
                            if (partners1.size() < AppConfig.LIST_PAGE_SIZE) {
                                pListView.setPullLoadEnable(false);
                            } else {
                                pListView.setPullLoadEnable(true);
                            }
                        } else {
                            page--;
                            pListView.setPullLoadEnable(false);
                            UIHelper.ToastMessage(getActivity(), "没有数据");
                        }
                        pListView.stopLoadMore();
                    }
                });

            }
        });
    }

    /**
     * 按角色分类
     *
     * @param input
     */
    public void sortByRole(String input) {
        role.clear();
        if (input.contains("技术")) {
            role.add("技术");
        }
        if (input.contains("运营")) {
            role.add("运营");
        }
        if (input.contains("产品")) {
            role.add("产品");
        }
        if (input.contains("销售")) {
            role.add("销售");
        }
        if (input.contains("设计")) {
            role.add("设计");
        }
        onRefresh();
    }

    /**
     * 按合伙人等级分类
     *
     * @param result
     */
    public void sortByLevel(List<Integer> result) {
        level = result;
        onRefresh();
    }

    /**
     * 按时间投入排序
     *
     * @param result
     */
    public void sortByTime(List<String> result) {
        times = result;
        onRefresh();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_partner_partner_friends:
                changeFriendBar(0);
                break;
            case R.id.ll_partner_partner_jlq:
                changeFriendBar(1);
                break;
            case R.id.ll_partner_partner_tlz:
                changeFriendBar(2);
                break;
        }
    }

    /**
     * 更改蓝色状态位置
     *
     * @param i
     */
    private void changeFriendBar(int i) {
        if (i == 0) {
            tvFriendBarFriend.setVisibility(View.VISIBLE);
            tvFriendBarJlq.setVisibility(View.INVISIBLE);
            tvFriendBarTlz.setVisibility(View.INVISIBLE);
            change2Now(indexContact, 0);
            indexContact = 0;
        } else if (i == 1) {
            tvFriendBarFriend.setVisibility(View.INVISIBLE);
            tvFriendBarJlq.setVisibility(View.VISIBLE);
            tvFriendBarTlz.setVisibility(View.INVISIBLE);
            change2Now(indexContact, 2);
            indexContact = 2;
        } else if (i == 2) {
            tvFriendBarFriend.setVisibility(View.INVISIBLE);
            tvFriendBarJlq.setVisibility(View.INVISIBLE);
            tvFriendBarTlz.setVisibility(View.VISIBLE);
            change2Now(indexContact, 1);
            indexContact = 1;
        }
    }

    public interface MainPartnerListener {

    }

    private ViewFlipper viewFlipper;


    private int partnerNow = 0;             //大选择栏位置

    /*获取当前位置*/
    public int getContactIndex() {
        return indexContact;
    }

    /**
     * 切换viewflipper的视图
     */
    private void changeNow(int from, int to) {
        if (from == to) {
            return;
        }
        while (from < to) {
            viewFlipper.showNext();
            from++;
        }
        while (from > to) {
            viewFlipper.showPrevious();
            from--;
        }
    }

    /**
     * 切换联系人viewflipper的视图
     */
    private void change2Now(int from, int to) {
        if (from == to) {
            return;
        }
        while (from < to) {
            vfContacts.showNext();
            from++;
        }
        while (from > to) {
            vfContacts.showPrevious();
            from--;
        }
    }

    public void doSwitch(int i) {
        switch (i) {
            case 0:
                changeNow(partnerNow, 0);
                partnerNow = 0;
                break;
            case 1:
                changeNow(partnerNow, 1);
                partnerNow = 1;
                break;
            case 2:
                changeNow(partnerNow, 2);
                partnerNow = 2;
                break;
            default:
                break;
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_partner, container, false);
        viewFlipper = (ViewFlipper) view.findViewById(R.id.vf_fragment_partner);


        partnerService = new PartnerServiceImpl();
        partnerAdapter = new ItemPartnerAdapter(getParentActivity(), partners);

        pListView = (WaterDropListView) view.findViewById(R.id.wl_partner);
        pListView.setWaterDropListViewListener(this);
        pListView.setPullLoadEnable(true);
        pListView.setAdapter(partnerAdapter);

        pListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position < 1 || position > partners.size()) {
                    //过滤刷新头部
                    return;
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putInt("userId", partners.get(position - 1).getUser_id());
                    UIHelper.showActivity(getParentActivity(), UserInfoActivity.class, bundle);
                }
            }
        });

        llFriendFriend = (LinearLayout) view.findViewById(R.id.ll_partner_partner_friends);
        llFriendJlq = (LinearLayout) view.findViewById(R.id.ll_partner_partner_tlz);
        llFriendTlz = (LinearLayout) view.findViewById(R.id.ll_partner_partner_jlq);

        tvFriendBarFriend = (TextView) view.findViewById(R.id.tv_partner_partner_blue_bar_1);
        tvFriendBarTlz = (TextView) view.findViewById(R.id.tv_partner_partner_blue_bar_2);
        tvFriendBarJlq = (TextView) view.findViewById(R.id.tv_partner_partner_blue_bar_3);

        llFriendFriend.setOnClickListener(this);
        llFriendJlq.setOnClickListener(this);
        llFriendTlz.setOnClickListener(this);


        /******
         * 聊天列表
         **********/
        inputMethodManager = (InputMethodManager) getParentActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        errorItem = (RelativeLayout) view.findViewById(R.id.rl_error_item);
        errorText = (TextView) errorItem.findViewById(R.id.tv_connect_errormsg);

        conversationList.addAll(loadConversationsWithRecentChat());
        mListView = (WaterDropListView) view.findViewById(R.id.wlv_partner_message_history);
        adapterMessage = new ChatAllHistoryAdapter(getParentActivity(), 1, conversationList);
        // 设置adapter
        mListView.setAdapter(adapterMessage);
        mListView.setPullLoadEnable(false);
        mListView.setWaterDropListViewListener(new WaterDropListView.IWaterDropListViewListener() {
            @Override
            public void onRefresh() {
                refreshMessage();
                mListView.stopRefresh();
            }

            @Override
            public void onLoadMore() {
            }
        });

        final String st2 = "不允许和自己聊天";
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                System.out.println("mList");
                if (position < 1) return;
                position = position - 1;
                EMConversation conversation = adapterMessage.getItem(position);
                String username = conversation.getUserName();
                System.out.println(username);
                if (username.equals(AppContext.getInstance().getUserId() + ""))
                    Toast.makeText(getParentActivity(), st2, Toast.LENGTH_SHORT).show();
                else {
                    // 进入聊天页面
                    Intent intent = new Intent(getParentActivity(), ChatActivity.class);
                    if (conversation.isGroup()) {
//                        if (conversation.getType() == EMConversation.EMConversationType.ChatRoom) {
//                            // it is group chat
//                            intent.putExtra("chatType", ChatActivity.CHATTYPE_CHATROOM);
//                            intent.putExtra("groupId", username);
//                        } else {
                        // it is group chat
//                        }
                    } else {
                        // it is single chat
                        intent.putExtra(ChatActivity.CHAT_TO_ID, Integer.valueOf(username));
                        User u = UserUtils.getUserInfo(username);
                        if(null == u){
                            intent.putExtra(ChatActivity.CHAT_TO_NAME, "未知");
                        }else{
                            intent.putExtra(ChatActivity.CHAT_TO_NAME, u.getNick());
                        }

                        startActivity(intent);
                    }

                }
            }
        });

        //长按删除
        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int i, long l) {

                final AlertDialog alertDialog = new AlertDialog(getParentActivity());
                alertDialog.setTitle("警告");
                alertDialog.setMessage("请确认是否删除该会话?删除后无法恢复！");
                alertDialog.setNegativeButton("点错了", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        alertDialog.dismiss();
                    }
                });
                alertDialog.setPositiveButton("删除", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (i < 1) return;
                        EMConversation conversation = adapterMessage.getItem(i - 1);
                        conversationList.remove(i - 1);
                        EMChatManager.getInstance().deleteConversation(conversation.getUserName(), false, true);
                        adapterMessage.notifyDataSetChanged();
                        alertDialog.dismiss();
                    }
                });
                return true;
            }
        });
        // 注册上下文菜单
//        registerForContextMenu(mListView);

//        mListView.setOnTouchListener(new View.OnTouchListener() {
//
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                // 隐藏软键盘
//                hideSoftKeyboard();
//                return false;
//            }
//
//        });
        // 搜索框
        query = (EditText) view.findViewById(R.id.query);
        String strSearch = "搜索";
        query.setHint(strSearch);
        // 搜索框中清除button
        clearSearch = (ImageButton) view.findViewById(R.id.search_clear);
        query.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                adapterMessage.getFilter().filter(s);
                if (s.length() > 0) {
                    clearSearch.setVisibility(View.VISIBLE);
                } else {
                    clearSearch.setVisibility(View.INVISIBLE);
                }
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void afterTextChanged(Editable s) {
            }
        });
        clearSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                query.getText().clear();
                hideSoftKeyboard();
            }
        });


        /******
         * 聊天列表
         **********/

        vfContacts = (ViewFlipper) view.findViewById(R.id.vf_partner_contact);

        /*******我的好友*******/
        cfListView = (ListView) view.findViewById(R.id.lv_partner_contact_friends);
        sidebar = (Sidebar) view.findViewById(R.id.sidebar);
        sidebar.setListView(cfListView);

        contactList = new ArrayList<User>();
        // 把"申请与通知"添加到首位


        // 设置adapter
        adapterContact = new ContactAdapter(getParentActivity(), R.layout.row_contact, contactList);
        cfListView.setAdapter(adapterContact);
        cfListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String username = adapterContact.getItem(position).getUsername();
                if (Constant.NEW_FRIENDS_USERNAME.equals(username)) {
                    // 进入申请与通知页面
//                    User user = ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getContactList().get(Constant.NEW_FRIENDS_USERNAME);
//                    user.setUnreadMsgCount(0);
                    startActivity(new Intent(getParentActivity(), NewFriendsMsgActivity.class));
//                } else if (Constant.GROUP_USERNAME.equals(username)) {
//                    // 进入群聊列表页面
//                    startActivity(new Intent(getParentActivity(), GroupsActivity.class));
//                } else if (Constant.CHAT_ROOM.equals(username)) {
//                    //进入聊天室列表页面
//                    startActivity(new Intent(getParentActivity(), PublicChatRoomsActivity.class));
//                } else if (Constant.CHAT_ROBOT.equals(username)) {
//                    //进入Robot列表页面
//                    startActivity(new Intent(getParentActivity(), RobotsActivity.class));
                } else {
                    // demo中直接进入聊天页面，实际一般是进入用户详情页
                    startActivity(new Intent(getParentActivity(), ChatActivity.class).putExtra("userId", adapterContact.getItem(position).getUsername()));
                }
            }
        });

        cfListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    return true;
                }
                final User user = adapterContact.getItem(position);
                final AlertDialog pd = new AlertDialog(getParentActivity());
                pd.setTitle("提醒");
                pd.setMessage("确认删除该好友?");
                pd.setPositiveButton("确认", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        deleteContact(user);
                        pd.dismiss();
                    }
                });
                pd.setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pd.dismiss();
                    }
                });

                return true;
            }
        });
        friendsRefresh();

        /*group*/

        groupListView = (ListView) view.findViewById(R.id.partner_group_list);
        groupListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    // 加入公开群
//                    startActivityForResult(new Intent(getParentActivity(), PublicGroupsActivity.class), 0);
                } else {
                    // 进入群聊
                    Intent intent = new Intent(getParentActivity(), ChatActivity.class);
                    // it is group chat
                    intent.putExtra("chatType", ChatActivity.CHATTYPE_GROUP);
                    intent.putExtra("groupId", groupAdapter.getItem(position - 1).getGroupId());
                    startActivityForResult(intent, 0);
                }
            }

        });

        groupRefresh();


            /*讨论组初始化*/
        tlzlist = EMGroupManager.getInstance().getAllGroups();
        tlzListView = (ListView) view.findViewById(R.id.partner_tlz_list);

        tlzAdapter = new TlzAdapter(getParentActivity(), 1, tlzlist);
        tlzListView.setAdapter(tlzAdapter);
        tlzListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    // 新建讨论组
                    startActivityForResult(new Intent(getParentActivity(), NewTlzActivity.class), 0);
                } else {
                    // 进入群聊
                    Intent intent = new Intent(getParentActivity(), ChatActivity.class);
                    intent.putExtra("chatType", ChatActivity.CHATTYPE_GROUP);
                    intent.putExtra("groupId", tlzAdapter.getItem(position - 1).getGroupId());
                    startActivityForResult(intent, 0);
                }
            }

        });

        tlzRefresh();

        /*******联系人*******/
        changeFriendBar(0);

        onRefresh();

        registerSyncListeners();

        return view;
    }


    /**
     * 注册环信的监听器
     */
    private void registerSyncListeners() {
//        contactSyncListener = new HXContactSyncListener();
//        HXSDKHelper.getInstance().addSyncContactListener(contactSyncListener);
//
//        contactInfoSyncListener = new HXContactInfoSyncListener();
//        ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getUserProfileManager().addSyncContactInfoListener(contactInfoSyncListener);
//
//        gSyncListener = new GSyncListener();
//        HXSDKHelper.getInstance().addSyncGroupListener(gSyncListener);
//
//        tlzSyncListener = new TlzSyncListener();
//        HXSDKHelper.getInstance().addSyncTlzListener(tlzSyncListener);
    }


    /**
     * 讨论组刷新
     */
    public void tlzRefresh() {
        if (tlzListView != null) {
            tlzlist = EMGroupManager.getInstance().getAllGroups();
            tlzAdapter = new TlzAdapter(getParentActivity(), 1,
                    tlzlist);
            tlzListView.setAdapter(tlzAdapter);
            tlzAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 群组刷新
     */
    public void groupRefresh() {
        if (groupListView != null) {
            grouplist = EMGroupManager.getInstance().getAllGroups();
            if (grouplist == null) {
                grouplist = new ArrayList<EMGroup>();
            }
            groupAdapter = new GroupAdapter(getParentActivity(), 1,
                    grouplist);
            groupListView.setAdapter(groupAdapter);
            groupAdapter.notifyDataSetChanged();
        }
    }

    private Activity getParentActivity() {
        return MainActivity.getInstance();
    }

    /**
     * 隐藏输入法
     */
    void hideSoftKeyboard() {
        if (getParentActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getParentActivity().getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getParentActivity().getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public void setIndentityListener(MainPartnerListener listener) {
        this.mlistener = listener;
    }


    /**
     * 获取所有会话
     *
     * @return +
     */
    private List<EMConversation> loadConversationsWithRecentChat() {
        // 获取所有会话，包括陌生人
        Hashtable<String, EMConversation> conversations = EMChatManager.getInstance().getAllConversations();
        // 过滤掉messages size为0的conversation
        /**
         * 如果在排序过程中有新消息收到，lastMsgTime会发生变化
         * 影响排序过程，Collection.sort会产生异常
         * 保证Conversation在Sort过程中最后一条消息的时间不变
         * 避免并发问题
         */
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    //if(conversation.getType() != EMConversationType.ChatRoom){
                    sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                    //}
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }
        return list;
    }

    /**
     * 删除联系人
     */
    public void deleteContact(final User tobeDeleteUser) {
        String st1 = "确认删除";
        final String st2 = "删除失败";
        final ProgressDialog pd = new ProgressDialog(getParentActivity());
        pd.setMessage(st1);
        pd.setCanceledOnTouchOutside(false);
        pd.show();
        new Thread(new Runnable() {
            public void run() {
                try {
                    EMContactManager.getInstance().deleteContact(tobeDeleteUser.getUsername());
                    // 删除db和内存中此用户的数据
                    UserDao dao = new UserDao(getParentActivity());
                    dao.deleteContact(tobeDeleteUser.getUsername());
                    ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getContactList().remove(tobeDeleteUser.getUsername());
                    getParentActivity().runOnUiThread(new Runnable() {
                        public void run() {
                            pd.dismiss();
                            adapterContact.remove(tobeDeleteUser);
                            adapterContact.notifyDataSetChanged();

                        }
                    });
                } catch (final Exception e) {
                    getParentActivity().runOnUiThread(new Runnable() {
                        public void run() {
                            pd.dismiss();
                            Toast.makeText(getParentActivity(), st2 + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });

                }

            }
        }).start();

    }

    /**
     * 刷新消息
     */
    public void refreshMessage() {
        conversationList.clear();
        conversationList.addAll(loadConversationsWithRecentChat());
        if (adapterMessage != null)
            adapterMessage.notifyDataSetChanged();
    }

    /**
     * 刷新页面
     */
    public void friendsRefresh() {

        try {
            // 可能会在子线程中调到这方法
            getParentActivity().runOnUiThread(new Runnable() {
                public void run() {
                    getContactList();
                    adapterContact.notifyDataSetChanged();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        if (contactSyncListener != null) {
            HXSDKHelper.getInstance().removeSyncContactListener(contactSyncListener);
            contactSyncListener = null;
        }

//        if (blackListSyncListener != null) {
//            HXSDKHelper.getInstance().removeSyncBlackListListener(blackListSyncListener);
//        }

        if (contactInfoSyncListener != null) {
            ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getUserProfileManager().removeSyncContactInfoListener(contactInfoSyncListener);
        }
        super.onDestroy();
    }
//

    /**
     * 根据最后一条消息的时间排序
     */
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {
                if (con1.first == con2.first) {
                    return 0;
                } else if (con2.first > con1.first) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }

    @Override
    public void onResume() {
        super.onResume();
        friendsRefresh();
        refreshMessage();
    }


    /**
     * 获取联系人列表，并过滤掉黑名单和排序
     */
    private void getContactList() {
        contactList.clear();
        //获取本地好友列表
        Map<String, User> users = ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getContactList();

        if (users == null) {
            users = new HashMap<>();
        }

        Iterator<Map.Entry<String, User>> iterator = users.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, User> entry = iterator.next();
            if (!entry.getKey().equals(Constant.NEW_FRIENDS_USERNAME)
                    && !entry.getKey().equals(Constant.GROUP_USERNAME)
                    && !entry.getKey().equals(Constant.CHAT_ROOM)
                    && !entry.getKey().equals(Constant.CHAT_ROBOT)
                    )
                contactList.add(entry.getValue());
        }
        // 排序
        Collections.sort(contactList, new Comparator<User>() {

            @Override
            public int compare(User lhs, User rhs) {
                return lhs.getUsername().compareTo(rhs.getUsername());
            }
        });

        if (users.get(Constant.CHAT_ROBOT) != null) {
            contactList.add(0, users.get(Constant.CHAT_ROBOT));
        }
//        // 加入"群聊"和"聊天室"
//        if (users.get(Constant.CHAT_ROOM) != null)
//            contactList.add(0, users.get(Constant.CHAT_ROOM));
//        if (users.get(Constant.GROUP_USERNAME) != null)
//            contactList.add(0, users.get(Constant.GROUP_USERNAME));

        // 把"申请与通知"添加到首位
        if (users.get(Constant.NEW_FRIENDS_USERNAME) != null)
            contactList.add(0, users.get(Constant.NEW_FRIENDS_USERNAME));

    }

}
